package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosUserDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class KitePosMemUserHandler extends KitePosBaseUserHandler implements IKitePosSceneHandler {
    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    IOperateSceneInstService operateSceneInstService;

    @Override
    public void handle(KitePosHandlerContext context) {
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
        if (!KiteStringUtils.equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN, LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT)) {
            return;
        }
        Date createDate = querySceneInstService.getSceneInst(context.getSceneInstId()).getCreateDate();
        String createDateStr = KiteDateUtils.formatDate(createDate, KiteDateUtils.DATE_TIME_FORMAT_14);
        List<KitePosUserDTO> userList = new ArrayList<>();
        List<KiteInst> memOfferInsts = this.querySceneInstService.listInsts(context.getSceneInstId(), Lists.newArrayList(InstType.MEM_OFFER_INST)).stream().filter(offerInst -> {
            return KiteStringUtils.equalsAny(offerInst.getActionType().name(), ActionType.K.name(), ActionType.A.name(), ActionType.M.name(), ActionType.D.name());
        }).collect(Collectors.toList());

        for (KiteInst memOfferInst : memOfferInsts) {
            String userInfoJson = memOfferInst.getAttrValue("userInfo");
            if (KiteStringUtils.isEmpty(userInfoJson)) {
                continue;
            }
            List<Map> memUsers = JSONObject.parseArray(userInfoJson, Map.class);
            for (int i = 0; i < memUsers.size(); i++) {
                Map<String, Object> groupUserInfo = memUsers.get(i);

                KitePosUserDTO user = new KitePosUserDTO();
                user.setUserDiffCode("00");
                user.setChangeType("9");
                user.setUserId(KiteMapUtils.getString(groupUserInfo, "user_id"));
                user.setSerialNumber(KiteMapUtils.getString(groupUserInfo, "serial_number").toUpperCase());
                user.setName(KiteMapUtils.getString(groupUserInfo, "user_name"));
                user.setInstanceId(KiteMapUtils.getString(groupUserInfo, "instance_id"));
                /*operateSceneInstService
                    .putExtParameter(context.getSceneInstId(), "business_number", user.getSerialNumber());
                operateSceneInstService.putExtParameter(context.getSceneInstId(), "instanceId", user.getInstanceId());*/
                List<KitePosAttrDTO> attrList = new ArrayList<>();
                user.setOpenDate(KiteMapUtils.getString(groupUserInfo, "open_date"));
                String userLocation = querySceneInstService
                    .getCommonAttrValue(context.getSceneInstId(), "user_location");
                if (!KiteStringUtils.isEmpty(userLocation)) {
                    user.setProvinceCode(userLocation.split(",")[0]);
                    user.setCityCode(userLocation.split(",").length > 1 ? userLocation.split(",")[1] : "");
                    user.setDistrictCode(userLocation.split(",").length > 2 ? userLocation.split(",")[2] : "");
                }
                else {
                    // 没有用户归属地属性，用客户的区域信息
                    CuccContextCustDTO custDto = context.getCustDto();
                    user.setProvinceCode(custDto.getProvinceCode());
                    user.setCityCode(Optional.ofNullable(custDto.getLanId()).orElse(custDto.getEparchyCode()));
                    user.setDistrictCode(Optional.ofNullable(custDto.getRegionId()).orElse(""));
                }
                this.addUserSourceAttr(attrList, groupUserInfo, createDateStr);
                this.packageUserAttrs(attrList, user, context, createDateStr);

                userList.add(user);
            }
        }
        List<KitePosUserDTO> users = context.getPosDto().getUsers();
        if (users == null) {
            users = Lists.newArrayList();
        }
        users.addAll(userList);
        context.getPosDto().setUsers(users);
    }
}
